package com.assistant.utils;

import java.io.*;
import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * 查找某个目录下的所有文件内容是否包含特定的内容
 */
public class SearchFile implements Callable<Boolean> {
    private String path;
    private String searchContent;
    private String excludeFileName;

    public SearchFile(String path,String searchContent) {
        this(path,searchContent,null);
    }
    /**
     *
     * @param path  查找的文件路径
     * @param searchContent 需要查找的内容
     * @param excludeFileName 添加某个文件或者目录到白名单
     */
    public SearchFile(String path, String searchContent, String excludeFileName) {
        this.path = path;
        this.searchContent = searchContent;
        this.excludeFileName = excludeFileName;
    }

    @Override
    public Boolean call() throws Exception {
        File file=new File(path);
        if(file.isDirectory()){
            for(File f: Objects.requireNonNull(file.listFiles())){
                if(searchFile(f)){
                    return true;
                }
            }
            return false;
        }
        return fileIsContain(file,searchContent);
    }

    private boolean searchFile(File f) {
        if(f.isDirectory()){
            //遍历目录下的文件
            for(File file:f.listFiles()){
               if(searchFile(file)){
                   return true;
               }
            }
            return false;
        }else{
            //该文件是否包含该内容
            return fileIsContain(f,searchContent);
        }

    }

    private boolean fileIsContain(File f, String searchContent) {

        try( BufferedReader bufferedReader=new BufferedReader(new FileReader(f));) {
            String line;
            while((line=bufferedReader.readLine())!=null){
                if(line.equals(searchContent)){
                    return true;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("sorry,不能找到该文件:"+f.getAbsolutePath());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO异常");
            e.printStackTrace();
        }
        return false;
    }

}
